package com.xh.demo.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author wen
 * @apiNote TestGatewayFilterFactory
 * @since 2021-12-12
 */
@Slf4j
@Component
public class TestGatewayFilterFactory extends AbstractGatewayFilterFactory<TestGatewayFilterFactory.Config> {

    public TestGatewayFilterFactory() {
        super(Config.class);
    }

    /**
     * URL key.
     */
    public static final String URL_KEY = "url";

    @Override
    public GatewayFilter apply(Config config) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        log.info("【测试自定义网关过滤器工厂-TestGatewayFilterFactory】【{}】", config.getUrl());
        boolean valid = random.nextInt() % 2 == 0;
        return (exchange, chain) -> {
            if (valid) {
                return chain.filter(exchange);
            } else {
                exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
                return exchange.getResponse().setComplete();
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(URL_KEY);
    }

    public static class Config {

        String url;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

    }
}
